package com.byt.base.utils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;

import com.byt.base.BaseApplication;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;

/**
 * 文件处理util
 */
public class FileUtil {

    public static final String ROOT_DIR = "Android/data/";
    public static final String MP3 = ".mp3";
    public static final String LRC = ".lrc";
    private static final int EOF = -1;
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    private FileUtil() {
    }

    public static String getAPPChashPath(Context mContext) {
        String cachePath;
        if (!TextUtils.isEmpty(Environment.getExternalStorageState()) && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            //外部存储可用
            cachePath = Environment.getExternalStorageDirectory() + "/" + mContext.getPackageName();
        } else {
            //外部存储不可用
            cachePath = Environment.getDownloadCacheDirectory().toString() + "/" + mContext.getPackageName(); // 现在缓存目录
        }
        return cachePath;
    }

    /**
     * 基本目录
     *
     * @param context
     * @return
     */
    public static String getBaseDirs(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/";
        return mkdirs(dir);
    }

    /**
     * 图片目录
     *
     * @return
     */
    public static String getPicDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/Pic/";
        return mkdirs(dir);
    }

    /**
     * 保存水印图片
     *
     * @return
     */
    public static String getWaterPicDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/waterPic/";
        return mkdirs(dir);
    }

    /**
     * 压缩文件目录
     *
     * @return
     */
    public static String getCompressDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/Compress/";
        return mkdirs(dir);
    }

    /**
     * 日志目录
     *
     * @return
     */
    public static String getLogDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/Log/";
        return mkdirs(dir);
    }

    /**
     * 歌曲目录
     *
     * @return
     */
    public static String getMusicDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/Music/";
        return mkdirs(dir);
    }

    /**
     * 音频文件
     *
     * @return
     */
    public static String getAudioDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/audio/";
        return mkdirs(dir);
    }

    /**
     * 视频文件
     *
     * @return
     */
    public static String getVideoDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/Video/";
        return mkdirs(dir);
    }

    /**
     * 歌词文件
     *
     * @return
     */
    public static String getLrcDir(Context context) {
        String dir = getAPPChashPath(context) + "/xmxb/Lyric/";
        return mkdirs(dir);
    }


    public static String getMp3FileName(String title) {
        return title + MP3;
    }

    private static String mkdirs(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dir;
    }

    /**
     * 创建文件
     *
     * @param path
     * @param name
     * @return
     */
    public static File saveFile(String path, String name) {
        mkdirs(path);
        File tempfile = new File(path, name);
        if (!tempfile.exists()) {
            try {
                tempfile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return tempfile;
    }

    public static String getLrcFileName(String title) {
        return title + LRC;
    }


    public static File from(Context context, Uri uri) throws IOException {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        String fileName = getFileName(context, uri);
        String[] splitName = splitFileName(fileName);
        File tempFile = File.createTempFile(splitName[0], splitName[1]);
        tempFile = rename(tempFile, fileName);
        tempFile.deleteOnExit();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(tempFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (inputStream != null) {
            copy(inputStream, out);
            inputStream.close();
        }

        if (out != null) {
            out.close();
        }
        return tempFile;
    }

    /**
     * 获取文件名
     *
     * @param fileName
     * @return
     */
    static String[] splitFileName(String fileName) {
        String name = fileName;
        String extension = "";
        int i = fileName.lastIndexOf(".");
        if (i != -1) {
            name = fileName.substring(0, i);
            extension = fileName.substring(i);
        }

        return new String[]{name, extension};
    }

    /**
     * 根据uri获取文件路径
     *
     * @param context
     * @param uri
     * @return
     */
    static String getFileName(Context context, Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf(File.separator);
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

    /**
     * 根据uri获取真文件路径
     *
     * @param context
     * @param contentUri
     * @return
     */
    public static String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
        if (cursor == null) {
            return contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            String realPath = cursor.getString(index);
            cursor.close();
            return realPath;
        }
    }

    static File rename(File file, String newName) {
        File newFile = new File(file.getParent(), newName);
        if (!newFile.equals(file)) {
            if (newFile.exists()) {
                if (newFile.delete()) {
                    Log.d("FileUtil", "Delete old " + newName + " file");
                }
            }
            if (file.renameTo(newFile)) {
                Log.d("FileUtil", "Rename file to " + newName);
            }
        }
        return newFile;
    }

    static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        if (count > Integer.MAX_VALUE) {
            return -1;
        }
        return (int) count;
    }

    static long copyLarge(InputStream input, OutputStream output)
            throws IOException {
        return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]);
    }

    static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
            throws IOException {
        long count = 0;
        int n;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    /**
     * 文件是否存在
     *
     * @param path
     * @return
     */
    public static boolean fileIsExists(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        try {
            File f = new File(path);
            if (!isFileExists(f)) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static boolean isFileExists(File file) {
        if (!file.exists()) {
            return false;
        }
        return true;
    }

    /**
     * 创建文件夹
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static File createSDDirectory(String filePath) throws IOException {
        File file = new File(filePath);
        if (!isFileExists(file))
            file.mkdirs();
        return file;
    }

    /**
     * 创建文件
     *
     * @param filePath 文件路径
     * @param fileName 文件名
     * @throws IOException
     */
    public static File createFileDirectory(String filePath, String fileName) throws IOException {
        createSDDirectory(filePath);
        File file = new File(filePath + fileName);
        if (!isFileExists(file)) {
            file.createNewFile();
        }
        return file;
    }

    public static File saveBitmap(Context context, Bitmap bm, String picName) {
        File f = null;
        try {
            f = new File(getPicDir(context), picName + ".JPEG");
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }

    /**
     * 获取应用目录，当SD卡存在时，获取SD卡上的目录，当SD卡不存在时，获取应用的cache目录
     */
    public static String getDir(String name) {
        StringBuilder sb = new StringBuilder();
        if (isSDCardAvailable()) {
            sb.append(getExternalStoragePath());
        } else {
            sb.append(getCachePath());
        }
        sb.append(name);
        sb.append(File.separator);
        String path = sb.toString();
        if (createDirs(path)) {
            return path;
        } else {
            return null;
        }
    }

    /**
     * 获取应用的cache目录
     */
    public static String getCachePath() {
        File f = BaseApplication.mApplication.getCacheDir();
        if (null == f) {
            return null;
        } else {
            return f.getAbsolutePath() + "/";
        }
    }

    /**
     * 创建文件夹
     */
    public static boolean createDirs(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists() || !file.isDirectory()) {
            return file.mkdirs();
        }
        return true;
    }

    /**
     * 获取SD下的应用目录
     */
    public static String getExternalStoragePath() {
        StringBuilder sb = new StringBuilder();
        sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
        sb.append(File.separator);
        sb.append(ROOT_DIR);
        sb.append(File.separator);
        return sb.toString();
    }

    /**
     * 判断SD卡是否挂载
     */
    public static boolean isSDCardAvailable() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            return true;
        } else {
            return false;
        }
    }

    public static File saveWaterBitmap(Context context, Bitmap bm, String picName) {
        File f = null;
        try {
            f = new File(getWaterPicDir(context), picName + ".JPEG");
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }

    /**
     * 验证是不是文件
     *
     * @param fileName
     * @return
     */
    public static boolean isFileExist(String fileName) {
        File file = new File(fileName);
        file.isFile();
        return file.exists();
    }

    public static void delFile(String fileName) {
        File file = new File(fileName);
        if (file.isFile()) {
            file.delete();
        }
    }

    public static void deleteDir(String path) {
        File dir = new File(path);
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDir(file.getAbsolutePath());
        }
        dir.delete();
    }

    /**
     * 删除文件夹
     *
     * @param dir
     */
    public static void deleteDir(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDir(file);
        }
        dir.delete();
    }

    /**
     * 删除文本
     *
     * @param mFile
     * @return
     */
    public static boolean deleteFile(File mFile) {
        if (mFile.isFile() && mFile.exists()) {
            return mFile.delete();
        }
        return false;
    }

    public static String getReadableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    public static File getSaveFile(Context context) {
        File file = new File(context.getFilesDir(), "pic.jpg");
        return file;
    }
}